import { observable, action, toJS } from 'mobx';
import { message } from 'antd';
import * as Api from '../apis/unitSetApi';
import { WeaLocaleProvider } from 'ecCom';

const { getLabel } = WeaLocaleProvider;

/*
  本页面有很多可以优化的地方 比如
  map改成for
  使用count刷新页面可以不这样做
  由于开发的时间时间跨度比较大 很多代码忘记了 很多都可以复用的
*/
export default class CorrespondFieldStore {
  @observable expandedKeys = [];
  @observable checkKeys = [];
  @observable checkNodes = [];
  @observable count = 1;
  @observable degradeNode = [] // 点击降级的时候选中的节点
  @observable degradeBrotherId = '' // 点击降级的时候选中的节点ID
  @observable nodeBrother = [];
  @observable nodeBrotherShow = false;
  @observable exchangeFieldOpsData = []
  @observable fieldTypeOpsData = [];
  @observable datas = [];
  @observable selectAllStatus = 0; // 0 不选中 1选中
  @observable loading = false;
  @observable searchsBaseValue = '';
  @observable isBatch = false;

  @action.bound
  findTreeData(data, type, value, id) {
    // 本想做成for循环 找到值之后就不处理了  但是由于mobx的数组不支持for循环 只好遍历所有节点
    data.map((item) => {
      if (item.id == id) {
        item[type] = value;
        if (type == 'name') {
          this.checkXmlFormat(toJS(this.datas));
        }
      } else if (item.children && item.children.length > 0) {
        this.findTreeData(item.children, type, value, id);
      }
    });
  }

  @action.bound
  valueChange(type, value, id) {
    this.findTreeData(this.datas, type, value, id);
  }

  @action.bound
  onExpand(expandedKeys) {
    this.expandedKeys = expandedKeys;
  }

  @action.bound
  onCheck(ids, nodeids, nodes) {
    this.checkKeys = ids;
    this.checkNodes = nodes;
  }

  @action.bound
  onDrag(dragNode, targetNode, datas) {
    this.datas = datas;
  }

  @action.bound
  onDatasChange(datas) {
    this.handleData(datas);
    this.datas = datas;
  }

  handleData(datas) {
    for (let i = datas.length - 1; i >= 0; i--) {
      if (datas[i].deleted) {
        datas.splice(i, 1);
      } else if (datas[i].children && datas[i].children.length > 0) {
        datas[i].field = '1';
        datas[i].fieldSelectValue = '';
        datas[i].fieldInputValue = '';
        this.handleData(datas[i].children);
      }
    }
  }

  @action.bound
  setMobxState(params = {}) {
    Object.keys(params).map((key) => {
      this[key] = params[key];
    });
  }

  @action.bound
  moveSiblingNode(id, upward = true) {
    this.moveSiblingDataChange(this.datas, id, upward);
  }

  @action.bound
  moveSiblingDataChange(datas, id, upward = true) {
    let ind = -1;
    datas.forEach((item, index, arr) => {
      if (ind == index) {
        return;
      }
      if (arr[index].id == id) {
        let temp = upward ? arr[index - 1] : arr[index + 1];
        upward && arr.splice(Number(index) - 1, 2, arr[index], temp);
        !upward && arr.splice(index, 2, temp, arr[index]);
        this.count++;
        ind = index + 1;
        return;
      }
      if (item.children && item.children.length > 0) {
        this.moveSiblingDataChange(item.children, id, upward);
      }
    });
  }

  @action.bound
  isFirstNode(id, isFirst = true) {
    return this.findFirstNode(toJS(this.datas), id, isFirst);
  }

  @action.bound
  findFirstNode(datas, id, isFirst) {
    if (isFirst) {
      if (datas[0].id == id) {
        return [true];
      }
    } else if (datas[datas.length - 1].id == id) {
      return [true];
    }
    const flat = arr => [].concat(...arr);
    return flat(datas.map((item) => {
      if (item.children && item.children.length > 0) {
        return this.findFirstNode(item.children, id, isFirst);
      }
    }));
  }

  // 返回的是从子节点的所有父节点
  @action.bound
  findParentNodeId(datas, func, nodeArr) {
    if (!datas) return [];
    for (let i in datas) {
      nodeArr.push(datas[i]);
      if (func(datas[i])) {
        datas.splice(i, 1);
        return nodeArr;
      }
      if (datas[i].children) {
        const findChildren = this.findParentNodeId(datas[i].children, func, nodeArr);
        if (findChildren.length) return findChildren;
      }
      nodeArr.pop();
    }
    return [];
  }

  // 升级
  @action.bound
  onUpgrade(item) {
    let nodeArr = [];
    nodeArr = this.findParentNodeId(toJS(this.datas), data => data.id === item.id, nodeArr);
    if (nodeArr.length == 1) {
      message.warning(getLabel('514381', '该节点已经是最高级，不能升级'));
    } else if (nodeArr.length == 2) {
      const node = nodeArr[nodeArr.length - 1];
      node.hierarchy = '0';
      node.pid = '';
      this.handleHierarchy(node, false);
      this.datas.push(node);
      this.datas.forEach((data, index, arr) => data.id == nodeArr[0].id && arr.splice(index, 1, nodeArr[0]));
    } else {
      const grandPrentId = nodeArr[nodeArr.length - 3].id;
      this.changeUpgradeData(this.datas, grandPrentId, nodeArr);
    }
  }

  @action.bound
  changeUpgradeData(datas, grandPrentId, nodeArr) {
    datas.map((item) => {
      if (item.id == grandPrentId) {
        const node = nodeArr[nodeArr.length - 1];
        node.hierarchy = Number(item.hierarchy) + 1;
        node.pid = grandPrentId;
        this.handleHierarchy(node, false);
        item.children.push(node);
        this.changeUpgradeParentNode(item.children, nodeArr[nodeArr.length - 2].id, nodeArr);
        return;
      }
      if (item.children && item.children.length > 0) {
        this.changeUpgradeData(item.children, grandPrentId, nodeArr);
      }
    });
  }

  @action.bound
  changeUpgradeParentNode(data, id, nodeArr) {
    data.map((item) => {
      if (item.id == id) {
        item.children.forEach((datas, index, arr) => datas.id == nodeArr[nodeArr.length - 1].id && arr.splice(index, 1));
      }
    });
  }

  // 获取兄弟节点
  @action.bound
  getBrotherNode(node) {
    this.isBatch = false;
    this.nodeBrother = this.getDegradeBrotherNode(toJS(this.datas), data => data.id == node.id);
    if (toJS(this.nodeBrother).length == 0) {
      message.warning(getLabel('514382', '该节点不能降级'));
    } else if (toJS(this.nodeBrother).length == 1) {
      // this.degradeNode = node;
      const brotherNodeId = this.nodeBrother[0].id;
      this.onDegrade([node], brotherNodeId);
    } else {
      this.degradeNode = [node];
      this.nodeBrotherShow = true;
    }
  }

  // 获取降级节点的兄弟节点
  @action.bound
  getDegradeBrotherNode(datas, func) {
    if (!datas) return [];
    for (let i in datas) {
      if (func(datas[i])) {
        datas.splice(i, 1);
        return datas;
      }
      if (datas[i].children) {
        const BrotherNode = this.getDegradeBrotherNode(datas[i].children, func);
        if (BrotherNode.length) return BrotherNode;
      }
    }
    return [];
  }

  // 降级
  @action.bound
  onDegrade(nodes, brotherNodeId, checkIds = []) {
    let datas = toJS(this.datas);
    this.getDegradeTree(datas, brotherNodeId, nodes, checkIds);
    this.handleData(datas);
    this.datas = datas;
    this.checkKeys = [];
    this.degradeNode = [];
    this.nodeBrotherShow = false;
    this.degradeBrotherId = '';
    this.searchsBaseValue = '';
  }

  // 获取降级后的树
  @action.bound
  getDegradeTree(datas, brotherNodeId, nodes, nodeIds) {
    datas.map((item) => {
      if (item.id == brotherNodeId) {
        for (let i in nodes) {
          nodes[i].hierarchy = Number(item.hierarchy) + 1;
          nodes[i].pid = item.id;
          this.handleHierarchy(nodes[i], true);
          if (item.children) {
            item.children.push(nodes[i]);
          } else {
            item.children = [nodes[i]];
          }
          item.isParent = true;
        }
        return;
      }
      if (this.isBatch ? nodeIds.includes(item.id) : item.id == nodes[0].id) {
        item.deleted = true;
        return;
      }
      if (item.children && item.children.length > 0) {
        this.getDegradeTree(item.children, brotherNodeId, nodes, nodeIds);
      }
    });
  }

  // 选择降级的节点父节点
  @action.bound
  onSelectDegradeParentNode(degradeBrotherId) {
    this.degradeBrotherId = degradeBrotherId;
  }

  // 处理层级
  @action.bound
  handleHierarchy(node, degrade) {
    if (node.children) {
      node.children.map((item) => {
        item.pid = node.id;
        const hierarchy = item.hierarchy;
        item.hierarchy = degrade ? Number(hierarchy) + 1 : Number(hierarchy) - 1;
        if (item.children && item.children.length > 0) {
          this.handleHierarchy(item, degrade);
        }
      });
    }
  }

  // 获取数据treedata数据
  @action.bound
  getTreeData(unitId) {
    const params = {
      id: unitId,
      dataType: 1,
    };
    Api.getUnitField(params).then((data) => {
      if (data.dataInfoItem) {
        this.exchangeFieldOpsData = data.dataInfoItem.exchangeFieldOpsData;
        this.fieldTypeOpsData = data.dataInfoItem.fieldTypeOpsData;
        this.datas = data.dataInfoItem.datas;
      }
    });
  }

  // 获取数据treedata数据
  @action.bound
  onSaveTreeData(unitId) {
    this.end = false;
    this.ValidateTreeData(toJS(this.datas));
    if (this.end) {
      message.warning(getLabel('508377', '有必填项没有填写'));
      return;
    }
    this.checkXmlFormat(toJS(this.datas));
    if (this.end) {
      message.warning(getLabel('', 'XML节点名称不能以数字开头'));
      return;
    }
    this.loading = true;
    const params = {
      datas: JSON.stringify(this.datas),
      dataType: 1,
      id: unitId,
    };
    Api.saveFields(params).then((data) => {
      this.loading = false;
      if (data.api_status) {
        message.success(getLabel('22619', '保存成功'));
      }
    });
  }

  @action.bound
  onSelect(ids) {
    this.selectKeys = ids;
  }

  // 批量删除
  @action.bound
  batchDelete() {
    const datas = JSON.parse(JSON.stringify(this.datas));
    this.deleteItem(datas, toJS(this.checkKeys));
    this.checkKeys = [];
    this.checkNodes = [];
    this.datas = datas;
  }

  // 删除所选项
  @action.bound
  deleteItem(data, ids) {
    for (let i = data.length - 1; i >= 0; i--) {
      if (ids.includes(data[i].id)) {
        data.splice(i, 1);
      } else if (data[i].children && data[i].children.length > 0) {
        this.deleteItem(data[i].children, ids);
      }
    }
  }

  @action.bound
  init() {
    this.expandedKeys = [];
    this.selectKeys = [];
    this.checkKeys = [];
    this.checkNodes = [];
    this.datas = [];
  }

  // 必填校验
  ValidateTreeData(data) {
    for (let i = 0; i < data.length; i++) {
      if (
        data[i].name.trim() == '' ||
        (
          (data[i].children == null || data[i].children.length == 0) &&
          (
            (data[i].field == '1' && data[i].fieldSelectValue == '') ||
            (data[i].field == '2' && data[i].fieldInputValue.trim() == '')
          )
        )
      ) {
        this.end = true;
        return;
      }
      if (this.end) return;
      if (data[i].children && data[i].children.length > 0) {
        this.ValidateTreeData(data[i].children);
      }
    }
  }

  @action.bound
  selectAll(value) {
    let ids = [];
    if (value == '1') {
      this.getAllIds(toJS(this.datas), ids);
      this.checkKeys = ids;
    } else if (value == '0') {
      this.checkKeys = [];
    }
  }

  getAllIds(data, ids = []) {
    for (let i = 0; i < data.length; i++) {
      ids.push(data[i].id);
      if (data[i].children && data[i].children.length > 0) {
        this.getAllIds(data[i].children, ids);
      }
    }
  }

  checkXmlFormat(data) {
    const regExp = new RegExp(/^\d/);
    for (let i = 0; i < data.length; i++) {
      if (regExp.test(data[i].name.trim())) {
        this.end = true;
        return;
      }
      if (data[i].children && data[i].children.length > 0) {
        this.checkXmlFormat(data[i].children);
      }
    }
  }

  // 检查是否是同一个父节点
  @action.bound
  checkIsSameParent(upgrade = false) {
    this.isBatch = true;
    const nodes = toJS(this.checkNodes);
    const pid = nodes[0].pid || '';
    const nodeIds = [nodes[0].id];
    for (let i = 1; i < nodes.length; i++) {
      nodeIds.push(nodes[i].id);
      const nodePid = nodes[i].pid || '';
      if (pid != nodePid) {
        message.warning(getLabel('', '选中节点中不是同一个父节点'));
        return;
      }
    }
    !upgrade && this.getBatchBrotherNode(pid, nodeIds);// 降级的操作
    upgrade && this.batchUpgrade(pid, nodes);// 升级的操作
  }

  // 获取兄弟节点
  @action.bound
  getBatchBrotherNode(pid, nodeIds) {
    const nodeBrothers = [];
    this.getBatchDegradeBrotherNode(toJS(this.datas), pid, nodeIds, nodeBrothers);
    this.nodeBrother = nodeBrothers;
    if (toJS(this.nodeBrother).length == 0) {
      message.warning(getLabel('', '选中节点不能降级'));
    } else if (toJS(this.nodeBrother).length == 1) {
      const brotherNodeId = this.nodeBrother[0].id;
      this.onDegrade(toJS(this.checkNodes), brotherNodeId, nodeIds);
    } else {
      this.degradeNode = toJS(this.checkNodes);
      this.nodeBrotherShow = true;
    }
  }

  // 获取降级节点的兄弟节点
  getBatchDegradeBrotherNode(datas, pid, nodeIds, nodeBrothers) {
    if (pid === '') {
      for (let i in datas) {
        if (!nodeIds.includes(datas[i].id)) {
          nodeBrothers.push(datas[i]);
        }
      }
      return;
    }
    for (let i in datas) {
      if (datas[i].id == pid) {
        for (let l in datas[i].children) {
          if (!nodeIds.includes(datas[i].children[l].id)) {
            nodeBrothers.push(datas[i].children[l]);
          }
        }
        return;
      }
      if (datas[i].children && datas[i].children.length > 0) {
        this.getBatchDegradeBrotherNode(datas[i].children, pid, nodeIds, nodeBrothers);
      }
    }
  }

  @action.bound
  batchUpgrade(pid) {
    const datas = toJS(this.datas),
      checkNodes = toJS(this.checkNodes);
    let nodeArr = [];
    // 得到的nodeArr
    nodeArr = this.findParentNodeId(toJS(this.datas), data => data.id === checkNodes[0].id, nodeArr);
    if (nodeArr.length == 1) {
      return message.warning;
    }
    for (let i in datas) {
      if (datas[i].id == pid) {

      }
    }
  }
}
